package org.wisdom.client;

import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import org.wisdom.response.Result;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.UUID;

@Component
@ConfigurationProperties(prefix = "mt")
@Slf4j
public class MTClient {

    private final RestTemplate restTemplate = new RestTemplate();
    private String token;

    private String consoleUrl;
    private String coreUrl;
    private String bucketName;
    private String username;
    private String password;

    @PostConstruct
    public void init() {
        try {
            auth();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException();
        }
    }

    private void auth() {
        // 登录
        String fullUrl = this.consoleUrl + "/op/login";
        // 请求体
        HashMap<String, String> map = new HashMap<>();
        map.put("username", this.username);
        map.put("password", this.password);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<HashMap<String, String>> requestEntity = new HttpEntity<>(map, headers);

        ResponseEntity<Result<String>> responseEntity = restTemplate.exchange(fullUrl, HttpMethod.POST, requestEntity, new ParameterizedTypeReference<Result<String>>() {});
        token = responseEntity.getBody().getData();
    }

    public String upload(MultipartFile file) throws IOException {
        // 生成文件路径
        LocalDateTime localDateTime = LocalDateTime.now();
        String prefix = localDateTime.getYear() + "/" + localDateTime.getMonthValue() + "/" + localDateTime.getDayOfMonth();

        String fileName = file.getOriginalFilename();
        String extendName = fileName.substring(fileName.lastIndexOf("."));
        String newFilename = UUID.randomUUID() + extendName;

        String fullUrl = this.coreUrl + "/" + this.bucketName + "/" + prefix + "/" + newFilename;
        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.parseMediaType(file.getContentType()));
        headers.setBearerAuth(token);

        // 创建HttpEntity，包含字节数组和请求头
        HttpEntity<byte[]> requestEntity = new HttpEntity<>(file.getBytes(), headers);

        // 发送POST请求
        try {
            restTemplate.postForEntity(fullUrl, requestEntity, Result.class);
        } catch (HttpClientErrorException e) {
            // 如果未认证则去重新登录
            if (e.getStatusCode().equals(HttpClientErrorException.Unauthorized.class)) {
                auth();
            }
            throw new RuntimeException("上传文件失败：" + e.getStatusText());
        }

        return fullUrl;
    }

    public String getConsoleUrl() {
        return consoleUrl;
    }

    public void setConsoleUrl(String consoleUrl) {
        this.consoleUrl = consoleUrl;
    }

    public String getCoreUrl() {
        return coreUrl;
    }

    public void setCoreUrl(String coreUrl) {
        this.coreUrl = coreUrl;
    }

    public String getBucketName() {
        return bucketName;
    }

    public void setBucketName(String bucketName) {
        this.bucketName = bucketName;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}
